﻿using AutoTask.DAL;
using AutoTask.Model;
using RpcCacheClient.Interface;
using RpcHelper;
using RpcHelper.Error;

namespace AutoTask.Collect.Collect
{
    internal class AutoTaskCollect : IAutoTaskCollect
    {
        private IAutoTaskDAL _BasicDAL;
        private ICacheController _Cache;
        public AutoTaskCollect(IAutoTaskDAL dal, ICacheController cache)
        {
            _Cache = cache;
            _BasicDAL = dal;
        }
        public BasicTask[] GetTasks(long regionId)
        {
            return _BasicDAL.GetTaskList(regionId);
        }
        public RemoteTask GetTask(Guid id, int verNum)
        {
            string key = string.Join("_", "Task", id.ToString("N"), verNum);
            if (_Cache.TryGet(key, out RemoteTask task))
            {
                return task;
            }
            task = this._BasicDAL.GetTask(id);
            _Cache.Set(key, task, new TimeSpan(1, 0, 0, 0, 0));
            return task;
        }
        public TaskState GetTaskState(Guid id)
        {
            return this._BasicDAL.GetTaskState(id);
        }

        public void StopTask(Guid id, string error)
        {
            long errorId = LocalErrorManage.GetErrorId(error);
            this._BasicDAL.StopTask(id, errorId);
        }



        public void SetTaskTime(Guid id, DateTime execTime)
        {
            this._BasicDAL.SetTaskTime(id, execTime);
        }

        public bool BeginExec(Guid id, DateTime next, int verNum, out int ver)
        {
            ver = Tools.GetRandom();
            return this._BasicDAL.BeginExec(id, next, verNum, ver);
        }

        public void ExecEnd(Guid id)
        {
            this._BasicDAL.EndExec(id);
        }
    }
}
